<?php

namespace extend;

use extend\cos\Cos;
use qcloudcos\Cosapi;
use think\Config;
use think\File;
use think\Log;


/**
 * Created by mask.
 * User: mask
 * Date: 2016/8/30
 * Time: 16:33
 */
class Tool {

	/**
	 * 是否在微信浏览器中
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return bool
	 */
	public static function isInWeChat() {
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if ( strpos( $user_agent, 'MicroMessenger' ) === FALSE ) {
			return 0;
		} else {
			return 1;
		}
	}

	/**
	 * @param $file
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return bool
	 */
	public static function delImage( $file )
	{
		//确保文件安全
		if(strpos($file,'..')!==FALSE)
		{
			return FALSE;
		}
		if ( is_file( $file ) ) {
			unlink( $file );
		} elseif ( is_file( self::getDocumentRoot() . 'public' . $file ) ) {
			unlink( self::getDocumentRoot() . 'public' . $file );
		}
		return TRUE;
	}
	
	/**
	 * @param     $money
	 * @param int $sub
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return mixed
	 */
	public static function formatMoney( $money, $sub = 3 ) {
		return number_format( $money, $sub, '.', '' );
	}


	public static function httpPost( $url, $data = NULL,$ssl=FALSE,$useCert=FALSE, $timeout = 60 ) {
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_POST, 1 );
		//data
		if ($data) {

			curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );

		}
		//严格校验
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
		if($useCert){
			//设置证书
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, SSLCERT_PATH);
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, SSLKEY_PATH);
		}
		//要求结果为字符串且输出到屏幕上
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
		curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
		curl_setopt( $ch, CURLOPT_HEADER, FALSE );


		$file_contents = curl_exec( $ch );
		if(!$file_contents)
		{
			Log::write("curl_error:".curl_error($ch));
			Log::write("curl_error:".var_export(curl_getinfo($ch),TRUE));
		}
		curl_close( $ch );
		return $file_contents;

	}

	/**
	 * @param       $url
	 * @param array $param
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return mixed
	 */
	public static function httpGet( $url, $param = [ ] ) {
		if ( $param ) {
			$url .= '?' . self::arrToUrlParam( $param );
		}
		$ch      = curl_init();
		$timeout = 20;
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_HEADER, 0 );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
		$file_contents = curl_exec( $ch );
		curl_close( $ch );

		return $file_contents;
	}

	/**
	 * 数组转url参数
	 * 并进行urlencode
	 *
	 * @param $arr
	 *
	 * @return string
	 */
	public static function arrToUrlParam( $arr ) {
		$param = '';
		if ( $arr ) {
			foreach ( $arr as $key => $val ) {
				$param .= empty( $param ) ? '' : '&';
				$param .= $key . '=' . urlencode( $val );
			}
		}
		unset( $arr );

		return $param;
	}
	

	/**
	 * 生成文件目录
	 *
	 * @param $path
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 */
	public static function makeDir( $path ) {
		if ( ! is_dir( $path ) ) {
			mkdir( $path ,0777,true);
		}
	}

	/**
	 * 获取根目录
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return string
	 */
	public static function getDocumentRoot() {
		return ROOT_PATH ? ROOT_PATH : $_SERVER['DOCUMENT_ROOT'];
	}

	public static function getCurrentUrl()
	{
		$host=$_SERVER["HTTP_HOST"];
		return 'http://'.$host.$_SERVER["REQUEST_URI"];
	}
	/**
	 *
	 * 产生随机字符串，不长于32位
	 * @param int $length
	 * @param $only_num
	 * @return string
	 */
	public static function getNonceStr($length = 32,$only_num=FALSE)
	{
		if($only_num){
			$chars = "0123456789";
		}else{
			$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		}
		$str ="";
		for ( $i = 0; $i < $length; $i++ )  {
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
		}
		return $str;
	}
	
	/**
	 * 冒泡
	 * @param $data
	 *
	 * @return mixed
	 */
	public static function popSort($data){
		$length=count($data);
		for($k=1;$k<$length;$k++)
		{
			for($j=0;$j<$length-$k;$j++){
				if($data[$j]>$data[$j+1]){
					$temp =$data[$j+1];
					$data[$j+1] =$data[$j] ;
					$data[$j] = $temp;
				}
			}
		}
		return $data;
	}

	/**
	 * 删除内容-限定条件：超过时间
	 * @param $dir
	 * @param $expire
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 */
	public  static function deleteDir($dir,$expire=0)
	{
		if (is_dir($dir)) {
			if ($dp = opendir($dir)) {
				$now=time();
				while (($file=readdir($dp)) != false) {
					if($file!='.' && $file!='..') {
						$filename=$dir.DS.$file;
						if(is_dir($filename))
						{
							self::deleteDir($filename);
						}elseif(is_file($filename) && (!$expire || ($now-filemtime($filename))>$expire))
						{
							unlink( $filename);
						}
					}
				}
				closedir($dp);
			}
			rmdir($dir);
		}
	}

	/**
	 * 根据两个坐标计算地址
	 * @param $n1
	 * @param $e1
	 * @param $n2
	 * @param $e2
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return mixed
	 */
	public static function calcDistance($n1, $e1, $n2, $e2)
	{
		//$n1=114.277852;
		//$e1=22.72743;
		$jl_jd = 102834.74258026089786013677476285;
        $jl_wd = 111712.69150641055729984301412873;
        $b = abs(($e1 - $e2) * $jl_jd);
		$a = abs(($n1 - $n2) * $jl_wd);
        return sqrt(($a * $a + $b * $b));
	}

	/**
	 * 格式化距离显示
	 * @param $distance
	 *
	 * @Version 1.7.3
	 * @Author  mask
	 * @return string
	 */
	public static function formatDistance($distance)
	{
		if((int)$distance>=1000)
		{
			$distance=self::formatMoney($distance/1000,1).'千米';
		}else
		{
			$distance=$distance.'米';
		}
		return $distance;
	}
	
	public static function formatDate($time)
	{
		$second=time()-$time;
		$result='';
		if($second<=60)
		{
			$result=$second.'秒前';
		}elseif($second<=3600)
		{
			$result=ceil($second/60).'分钟前';
		}elseif($second<=3600*24){
			$result=ceil($second/(3600*24)).'小时前';
		}else{
			$result=date("Y年m月d日",$time);
		}
		return $result;
	}
	
	public static function arrayToXml($arr){
		$xml = "";
		foreach ($arr as $key=>$val){
			if(is_array($val)){
				if (is_numeric($key)){
					$xml.=self::arrayToXml($val);
				}else
				{
					$xml.="<".$key.">".self::arrayToXml($val)."</".$key.">";
				}

			}else{
				if (is_numeric($val)){
					$xml.="<".$key.">".$val."</".$key.">";
				}else{
					$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
				}
			}
		}
		return $xml;
	}


	public static function refererUrl()
	{
		return isset($_SERVER['HTTP_REFERER'])&&$_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:url('home/index/index');
	}

	/**
	 * 上传图片到腾讯对象储存库
	 * @param      $img
	 * @param bool $delete 是否删除原图
	 *
	 * @Version 1.0
	 * @Author  masky
	 * @return array
	 */
	public static function putImageToCos($img,$delete=TRUE) {
		Cos::init();
		Cosapi::setTimeout(180);
		// 设置COS所在的区域，对应关系如下：
		//     华南  -> gz
		//     华东  -> sh
		//     华北  -> tj
		Cosapi::setRegion('gz');
		$srcPath=ROOT_PATH.'/public'.$img;
		$file_arr=explode('/',$img);
		$file_name=end($file_arr);
		$dstPath = "/".$file_name;
		$result = Cosapi::upload(Config::get('system.cos')['bucket'],$srcPath,$dstPath);
		if($result['code']==0 && $delete){
			self::delImage($img);
		}
		Log::write('cos:result======='.var_export($result,TRUE));
		return $result;
	}
	
	public static function uploadImageArray($files){
		$result=[];
		foreach ($files as $file){
			array_push($result,self::uploadImage($file));
		}
		return $result;
	}
	public static function uploadImage(File $file){
		$info=$file->move(ROOT_PATH."public/upload/");
		if($info)
		{
			$fullFilename=$info->getPath().DS.$info->getFilename();
			$fileName=str_replace('\\','/',$fullFilename);
			//压缩图片
			/*if(strpos($fileName,'.png')!==FALSE){
				imagepng($fileName,$fileName,2);
			}else{
				imagejpeg($fileName,$fileName,2);
			}*/
			$root=str_replace('\\','/',ROOT_PATH).'public';
			$fileUrl= str_replace($root,'',$fileName);
			
			return $fileUrl;
		}else
		{
			return FALSE;
		}
	}
}